package top.milkbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import top.milkbox.domain.PostCollection;
import top.milkbox.domain.PostLike;
import top.milkbox.domain.User;
import top.milkbox.mapper.PostLikeMapper;
import top.milkbox.service.PostCollectionService;
import top.milkbox.mapper.PostCollectionMapper;
import org.springframework.stereotype.Service;
import top.milkbox.service.UserService;
import top.milkbox.utils.GuoUtilsDate;

/**
* @author xiaoguo
* @description 针对表【tb_post_collection(收藏表)】的数据库操作Service实现
* @createDate 2022-11-22 18:07:06
*/
@Service
public class PostCollectionServiceImpl extends ServiceImpl<PostCollectionMapper, PostCollection>
    implements PostCollectionService{

    @Autowired
    private PostCollectionMapper postCollectionMapper;

    @Autowired
    private UserService userService;

    @Override
    public boolean collection(String token, int postId) {
        User user = userService.getUserFromRedis(token);
        if(isCollection(user.getUserId(), postId)) { // 判断是否收藏
            log.debug("用户" + user.getUserId() + "已经收藏帖子" + postId + "了");
            return false;
        } else {
            log.debug("用户" + user.getUserId() + "未收藏帖子" + postId + "，正在收藏");
            PostCollection postCollection = new PostCollection();
            postCollection.setUserId(user.getUserId());
            postCollection.setPostId(postId);
            postCollection.setTime(GuoUtilsDate.getDateNow());
            return postCollectionMapper.insert(postCollection) == 1;
        }
    }

    @Override
    public boolean cancelCollection(String token, int postId) {
        User user = userService.getUserFromRedis(token);
        if(isCollection(user.getUserId(), postId)) { // 判断是否收藏
            log.debug("用户" + user.getUserId() + "已经收藏了，准备取消收藏");
            // 删除操作，通过user_id和post_id删除数据
            QueryWrapper<PostCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getUserId())
                    .eq("post_id", postId);
            return postCollectionMapper.delete(queryWrapper) == 1;
        } else {
            log.debug("用户" + user.getUserId() + "还没有收藏帖子" + postId);
            return false;
        }
    }

    @Override
    public boolean isCollection(int userId, int postId) {
        QueryWrapper<PostCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("post_id", postId);
        return postCollectionMapper.selectOne(queryWrapper) != null;
    }
}




